<template>
  <el-scrollbar class="side-scroll-bar">
    <div class="panel-container">

    <!-- <el-tabs v-model="firstTab" class="no-bottom-margin indent-left-margin">
      <el-tab-pane name="componentLib">
        <template #label>
          <span><svg-icon icon-class="el-set-up" /> {{i18nt('designer.componentLib')}}</span>
        </template> -->

      <el-collapse v-model="activeNames" class="widget-collapse">
        <el-collapse-item name="1" :title="i18nt('designer.containerTitle')">
          <draggable tag="ul" :list="containers" item-key="id" :group="{name: 'dragGroup', pull: 'clone', put: false}"
                     :clone="handleContainerWidgetClone" ghost-class="ghost" :sort="false"
                     :move="checkContainerMove" @end="onContainerDragEnd">
            <template #item="{ element: ctn }">
              <li class="container-widget-item" :title="ctn.displayName"
                  @dblclick="addContainerByDbClick(ctn)">
                <span><svg-icon :icon-class="ctn.icon" class-name="color-svg-icon" />{{ctn.options.label}}</span>
              </li>
            </template>
          </draggable>
        </el-collapse-item>

        <el-collapse-item name="2" title="待选项" class="search-item">
          <div class="search-item-input">
            <el-input placeholder="搜索关键字" v-model="position1" class="input-with-select" @blur="scrollToView(1)" @keyup.enter.native="scrollToView(1)">
            </el-input>
          </div>
          <div class="center-box" ref="list_1">
            <draggable tag="ul" :list="noSelectedList" item-key="id" :group="{name: 'dragGroup', pull: 'clone', put: false}"
                      :move="checkFieldMove"
                      :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
              <template #item="{ element: fld, index }">
                <li class="field-widget-item" :title="fld.options?.label"
                    @dblclick="addFieldByDbClick(fld)" :id="fld.options?.name || 'divider'">
                  <span><svg-icon :icon-class="fld.icon" class-name="color-svg-icon" />{{fld.options?.label}}</span>
                </li>
              </template>
            </draggable>
          </div>
        </el-collapse-item>
        <el-collapse-item class="search-item" name="3" title="已选项">
          <div class="search-item-input">
            <el-input placeholder="搜索关键字" v-model="position2" class="input-with-select" @blur="scrollToView(2)" @keyup.enter.native="scrollToView(2)">
            </el-input>
          </div>
          <div class="selected-box" ref="list_2">
            <ul>
              <p
                v-for="(item, index) in selectedList"
                :key="index"
                class="selected-p"
                :id="item.widgetList[0]?.options?.name"
              >
                <li v-if="item.widgetList.length > 0">
                  <span>
                    <img
                      class="del-img"
                      v-if="alwaysRequire.indexOf(item.widgetList[0]?.options?.name) == -1"
                      src="@/assets/vform/del.png"
                      @click="drawingItemDelete(index, selectedList, 'formDataNoselected')"
                    />
                    <span v-else style="padding: 12px;"></span>
                    {{ item.widgetList[0]?.options?.label }}
                  </span>
                  <span>
                    <el-button
                      v-if="item.widgetList[0]?.options?.label"
                      :disabled="alwaysRequire.indexOf(item.widgetList[0]?.options?.name) > -1"
                      :class="{
                        's-required': true,
                        's-required-active': item.widgetList[0]?.options?.required,
                      }"
                      @click="setRequired(item, index)"
                    >
                      必填
                    </el-button>
                    <el-button
                      :disabled="alwaysRequire.indexOf(item.widgetList[0]?.options?.name) > -1"
                      :class="{
                        's-required': true,
                        's-remind-active': item.widgetList[0]?.options?.onValidate,
                      }"
                      @click="setRemind(item, index)"
                    >
                      提醒
                    </el-button>
                  </span>
                </li>
                <template v-if="!item.widgetList.length > 1">
                  <li
                    v-for="(item1, index1) in item.options?.children"
                    :key="index1"
                  >
                    <span>
                      <img
                        class="del-img"
                        src="@/assets/vform/del.png"
                        @click="
                          drawingItemDelete(
                            index1,
                            item.options.children,
                            'children'
                          )
                        "
                      />
                      {{ item1.options.label }}
                    </span>
                    <span>
                      <el-button
                        disabled
                        :class="{
                          's-required': true,
                          's-required-active':
                            item.options.required,
                        }"
                        @click="setRequired(item1, index1)"
                      >
                        必填
                      </el-button>
                    </span>
                  </li>
                </template>
              </p>
            </ul>
          </div>
          </el-collapse-item>
      </el-collapse>

      <!-- </el-tab-pane>

      <el-tab-pane v-if="showFormTemplates()" name="formLib" style="padding: 8px">
        <template #label>
          <span><svg-icon icon-class="el-form-template" /> {{i18nt('designer.formLib')}}</span>
        </template>

        <template v-for="(ft, idx) in formTemplates">
          <el-card :bord-style="{ padding: '0' }" shadow="hover" class="ft-card">
            <el-popover placement="right" trigger="hover">
              <template #reference>
                <img :src="ft.imgUrl" style="width: 200px">
              </template>
              <img :src="ft.imgUrl" style="height: 600px;width: 720px">
            </el-popover>
            <div class="bottom clear-fix">
              <span class="ft-title">#{{idx+1}} {{ft.title}}</span>
              <el-button link type="primary" class="right-button" @click="loadFormTemplate(ft.jsonUrl)">
                {{i18nt('designer.hint.loadFormTemplate')}}</el-button>
            </div>
          </el-card>
        </template>
      </el-tab-pane>

    </el-tabs> -->

    </div>
  </el-scrollbar>
</template>

<script>
  import {containers as CONS, basicFields as BFS, advancedFields as AFS, customFields as CFS} from "./widgetsConfig"
  import {formTemplates} from './templatesConfig'
  import {addWindowResizeHandler, generateId} from "@/utils/util"
  import i18n from "@/utils/i18n"
  import axios from 'axios'
  import SvgIcon from "@/components/svg-icon/index"
  import { ElNotification } from 'element-plus'

  export default {
    name: "FieldPanel",
    mixins: [i18n],
    components: {
      SvgIcon
    },
    props: {
      designer: Object,
      title: {
        type: String,
        default: ""
      },
      selectedList: {
        type: Array,
        default: () => []
      },
      noSelectedList: {
        type: Array,
        default: () => []
      }
    },
    inject: ['getBannedWidgets', 'getDesignerConfig'],
    data() {
      return {
        position1:"",
        position2:"",
        alwaysRequire: [
          "coopName", "settlementCoopName", "masterSalesName","masterSalesRatio",
          "servicerName","departureStation","arrivalStation","flightDate",
          "businessDate","businessProduct","bookingType","SOPDimension",
          "planPieces","planWeight","planVolume","arrivalDate"
        ],
        designerConfig: this.getDesignerConfig(),

        firstTab: 'componentLib',

        scrollerHeight: 0,
        halfScrollHeight: '170px',
        activeNames: ['1', '2', '3', '4'],

        containers: [],
        basicFields: [],
        advancedFields: [],
        customFields: [],

        formTemplates: formTemplates
      }
    },
    computed: {
      //
    },
    created() {
      this.loadWidgets()
    },
    mounted() {
      // this.scrollerHeight = window.innerHeight - 56 + 'px';
      // addWindowResizeHandler(() => {
      //   this.$nextTick(() => {
      //     this.scrollerHeight = window.innerHeight - 56 + 'px';
      //   })
      // })
      this.initData();
    },
    methods: {
      renderForm(){
        this.$nextTick(() => {
          this.selectedList?.length > 0 && this.selectedList.forEach(item => {
            if(item.widgetList?.length){
                if (item.widgetList[0].options?.name && this.alwaysRequire.includes(item.widgetList[0].options.name)) {
                    item.widgetList[0].options.required = true
                }
            }
          })
        })
      },
      initData(){
        if(this.title.includes("进口")){
          this.alwaysRequire=[
            "coopName", "settlementCoopName", "masterSalesName","masterSalesRatio",
            "servicerName","arrivalStation","flightDate",
            "businessDate","businessProduct","bookingType","SOPDimension",
            "arrivalDate"
          ]
        }else{
          this.alwaysRequire=[
            "coopName", "settlementCoopName", "masterSalesName","masterSalesRatio",
            "servicerName","departureStation","arrivalStation","flightDate",
            "businessDate","businessProduct","bookingType","SOPDimension",
            "planPieces","planWeight","planVolume","arrivalDate"
          ]
        }
        this.renderForm()
      },
      getPosition(n, search, arr){
          let id = '';
          if(n === 2){
            arr.forEach((item, index) => {
              if(item.widgetList.length){
                if (item.widgetList[0].options.label.includes(search)) {
                  if (!id) {
                    id = item.widgetList[0].options.name
                  }
                }
              }
            })
          }
          if(n === 1){
            arr.forEach((item, index) => {
              if (item.options.label.includes(search)) {
                if (!id) {
                  id = item.options.name
                }
              }
            })
          }
          return id;
      },
      scrollToView(n) {
          let txt = this['position' + n]
          let arr = n === 1 ? this.noSelectedList : this.selectedList;
          let _X_ID = this.getPosition(n, txt, arr);
          if(n === 1 && "分割线".includes(txt)){
              let parent = this.$refs['list_1'];
              parent.scrollTo({
                  top: 0,
                  behavior: 'smooth'
              });
          }
          if(!!_X_ID){
              let target = document.querySelector('#'+_X_ID);
              let parent = this.$refs['list_'+n];
              let tTop = target?.offsetTop || 0;
              let pTop = parent?.$el?.offsetTop || 0;
              this.$nextTick(() => {
                parent.scrollTo({
                  top: tTop - pTop - 50,
                  behavior: 'smooth'
                });
              })
          }
      },
      drawingItemDelete(index, list, listKey) {
        // console.log('listKey', index, list, listKey)
        if (
          list[index].options.name === "coopName" ||
          list[index].options.name === "salesName" ||
          list[index].options.name === "expectDeparture" ||
          list[index].options.name === "controllerName" ||
          list[index].options.name === "routingPersonName" ||
          list[index].options.name === "servicerName"
        ) {
          ElNotification({
            type: 'warning',
            title: '提示',
            message: "必填项不可删除",
            position: 'bottom-right',
          })
        } else {
            list.splice(index, 1);
        }
      },
      seeData() {
        console.log('已选-panel', this.selectedList)
        console.log('待选-panel', this.noSelectedList)
      },
      setRequired(item, index) {
        // console.log(item, index)
        this.$nextTick(() => {
          if (this.alwaysRequire.indexOf(item.widgetList[0].options.name) > -1) {
            ElNotification({
              type: 'warning',
              title: '提示',
              message: "必填项不可删除",
              position: 'bottom-right',
            })
          } else {
            item.widgetList[0].options.required = !item.widgetList[0].options.required
            if(item.widgetList[0].options.required) {
              item.widgetList[0].options.onValidate = false
            }
          }
        })
      },
      // 提醒
      setRemind(item) {
        this.$nextTick(() => {
          item.widgetList[0].options.onValidate = !item.widgetList[0].options.onValidate
          if(item.widgetList[0].options.onValidate) {
            item.widgetList[0].options.required = false
          }
        })
      },
      isBanned(wName) {
        return this.getBannedWidgets().indexOf(wName) > -1
      },

      showFormTemplates() {
        if (this.designerConfig['formTemplates'] === undefined) {
          return true
        }

        return !!this.designerConfig['formTemplates']
      },

      loadWidgets() {
        this.containers = CONS.map(con => {
          return {
            key: generateId(),
            ...con,
            // displayName: this.i18n2t(`designer.widgetLabel.${con.type}`, `extension.widgetLabel.${con.type}`)
            displayName: con.options.label
          }
        }).filter(con => {
          return !con.internal && !this.isBanned(con.type)
        })

        this.basicFields = BFS.map(fld => {
          return {
            key: generateId(),
            ...fld,
            // displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
            displayName: fld.options.label
          }
        }).filter(fld => {
          return !this.isBanned(fld.type)
        })

        this.advancedFields = AFS.map(fld => {
          return {
            key: generateId(),
            ...fld,
            // displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
            displayName: fld.options.label
          }
        }).filter(fld => {
          return !this.isBanned(fld.type)
        })

        this.customFields = CFS.map(fld => {
          return {
            key: generateId(),
            ...fld,
            displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
          }
        }).filter(fld => {
          return !this.isBanned(fld.type)
        })
      },

      handleContainerWidgetClone(origin) {
        return this.designer.copyNewContainerWidget(origin)
      },

      handleFieldWidgetClone(origin) {
        return this.designer.copyNewFieldWidget(origin)
      },

      checkContainerMove(evt) {
        return this.designer.checkWidgetMove(evt)
      },

      checkFieldMove(evt) {
        return this.designer.checkFieldMove(evt)
      },

      onContainerDragEnd(evt) {
        //console.log('Drag end of container: ')
        //console.log(evt)
      },

      addContainerByDbClick(container) {
        this.designer.addContainerByDbClick(container)
      },

      addFieldByDbClick(widget) {
        this.designer.addFieldByDbClick(widget)
      },

      loadFormTemplate(jsonUrl) {
        this.$confirm(this.i18nt('designer.hint.loadFormTemplateHint'), this.i18nt('render.hint.prompt'), {
          confirmButtonText: this.i18nt('render.hint.confirm'),
          cancelButtonText: this.i18nt('render.hint.cancel')
        }).then(() => {
          axios.get(jsonUrl).then(res => {
            let modifiedFlag = false
            if (typeof res.data === 'string') {
              modifiedFlag = this.designer.loadFormJson( JSON.parse(res.data) )
            } else if (res.data.constructor === Object) {
              modifiedFlag = this.designer.loadFormJson(res.data)
            }
            if (modifiedFlag) {
              this.designer.emitHistoryChange()
            }

            this.$message.success(this.i18nt('designer.hint.loadFormTemplateSuccess'))
          }).catch(error => {
            this.$message.error(this.i18nt('designer.hint.loadFormTemplateFailed') + ':' + error)
          })
        }).catch(error => {
          console.error(error)
        })
      }

    }

  }
</script>

<style lang="scss" scoped>
  .color-svg-icon {
    -webkit-font-smoothing: antialiased;
    color: #7c7d82;
  }

  .side-scroll-bar {
    :deep(.el-scrollbar__wrap) {
      overflow-x: hidden;
    }
  }

  div.panel-container {
    padding-bottom: 10px;
  }

  .no-bottom-margin :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  .indent-left-margin {
    :deep(.el-tabs__nav) {
      margin-left: 20px;
    }
  }

  .el-collapse-item :deep(ul) > li {
    list-style: none;
  }

  .widget-collapse {
    border-top-width: 0;

    :deep(.el-collapse-item__header) {
      margin-left: 8px;
      font-weight: bold;
    }

    :deep(.el-collapse-item__content) {
      padding-bottom: 6px;

      ul {
        padding-left: 15px;  /* 重置IE11默认样式 */
        margin: 0;  /* 重置IE11默认样式 */
        margin-block-start: 0;
        margin-block-end: 0.25em;
        padding-inline-start: 10px;

        &:after {
          content: "";
          display: block;
          clear: both;
        }

        .container-widget-item, .field-widget-item {
          display: inline-block;
          height: 32px;
          line-height: 32px;
          width: 40%;
          margin: 2px 6px 6px 0;
          float: left;
          cursor: move;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
          background: #fff;
          border: 1px solid #e8e9eb;
          border-radius: 4px;
          padding: 0 8px;
        }

        .container-widget-item:hover, .field-widget-item:hover {
          background: #F1F2F3;
          border-color: $--color-primary;

          .color-svg-icon {
            color: $--color-primary;
          }
        }

        .drag-handler {
          position: absolute;
          top: 0;
          left: 160px;
          background-color: #dddddd;
          border-radius: 5px;
          padding-right: 5px;
          font-size: 11px;
          color: #666666;
        }
      }
    }
  }

  .el-card.ft-card {
    border: 1px solid #8896B3;
  }

  .ft-card {
    margin-bottom: 10px;

    .bottom {
      margin-top: 10px;
      line-height: 12px;
    }

    /*
    .image-zoom {
      height: 500px;
      width: 620px
    }
    */

    .ft-title {
      font-size: 13px;
      font-weight: bold;
    }

    .right-button {
      padding: 0;
      float: right;
    }

    .clear-fix:before, .clear-fix:after {
      display: table;
      content: "";
    }

    .clear-fix:after {
      clear: both;
    }
  }

  .is-disabled:first-child{
    background: url("@/assets/vform/require.png") no-repeat center center;
    background-size: 100% 100%;
  }
  .is-disabled:first-child:hover,
  .is-disabled:first-child:focus,
  .is-disabled:first-child:active {
    background: url("@/assets/vform/require.png") no-repeat center center;
    background-size: 100% 100%;
  }

  .s-required{
    height: 20px;
    line-height: 20px;
    padding: 0 10px;
    font-size: 10px;
    color: var(--theme-color-primary) !important;
    background: url("@/assets/vform/grey.png") no-repeat center center;
    background-size: 100% 100%;
  }

  .s-required-active{
    background: url("@/assets/vform/require.png") no-repeat center center;
    background-size: 100% 100%;
  }

  .search-item{
    position: relative;
    &-input{
      position: absolute;
      left: 60px;
      top: 5px;
    }
  }

  .center-box {
    max-height: 200px;
    overflow-y: scroll;
  }
  .selected-box {
    margin-top: -5px;
    max-height: 200px;
    overflow-y: scroll;
  }

  .selected-box ul li {
    font-size: 12px;
    padding: 0 10px 0 0;
    box-shadow: 0px 1px 0px 0px #EAEEF5;
    line-height: 36px;
    list-style: none;
    display: flex;
    align-items: center;
    justify-content: space-between;
    vertical-align: middle;
  }
  
  .del-img{
    float: left;
    margin: 8px 3px 0 3px;
  }

</style>
